/**
/**
 * 策略区域配置管理模块（新界面）
 * @author 运费系统团队
 * @description 支持新界面设计：左侧区域列表，中间计算规则，右侧重量区间规则
 */

function useStrategyAreaConfiguration() {
    const { ref, reactive, watch, computed, onMounted } = Vue;
    // =====================================
    // 响应式数据定义
    // =====================================
    
    // 主要数据
    const currentStrategyId = ref('');
    const strategyAreaDetails = ref([]); // 策略区域详情列表
    const loading = ref(false);
    const saving = ref(false);
    
    // 选中状态
    const selectedAreaId = ref('');
    const selectedAreaDetail = ref(null);
    
    // 编辑状态
    const isEditing = ref(false);
    const showAreaConfigModal = ref(false);
    
    // 区域配置表单
    const areaConfigForm = reactive({
        strategyId: '',
        areaId: '',
        areaName: '',
        // 计算规则参数
        firstWeightKg: '',
        firstWeightFee: '',
        additionalWeightKg: '',
        additionalWeightFee: '',
        volumetricWeightRatio: '',
        status: 1,
        // 重量区间规则
        weightSegmentRules: []
    });
    
    // 新增重量区间规则的表单
    const newWeightRule = reactive({
        upperBound: '',
        freight: '',
        isAdding: false
    });
    
    // =====================================
    // 计算属性
    // =====================================
    
    // 当前选中区域的重量规则
    const currentWeightRules = computed(() => {
        return areaConfigForm.weightSegmentRules || [];
    });
    
    // 是否有未保存的更改
    const hasUnsavedChanges = computed(() => {
        return isEditing.value && (
            areaConfigForm.firstWeightKg !== selectedAreaDetail.value?.firstWeightKg ||
            areaConfigForm.firstWeightFee !== selectedAreaDetail.value?.firstWeightFee ||
            areaConfigForm.additionalWeightKg !== selectedAreaDetail.value?.additionalWeightKg ||
            areaConfigForm.additionalWeightFee !== selectedAreaDetail.value?.additionalWeightFee ||
            areaConfigForm.volumetricWeightRatio !== selectedAreaDetail.value?.volumetricWeightRatio
        );
    });
    
    // =====================================
    // 监听器
    // =====================================
    
    // 监听策略变化
    watch(currentStrategyId, (newStrategyId) => {
        if (newStrategyId) {
            loadStrategyAreaDetails();
        } else {
            strategyAreaDetails.value = [];
            selectedAreaId.value = '';
            selectedAreaDetail.value = null;
        }
    });
    
    // 监听选中区域变化
    watch(selectedAreaId, (newAreaId) => {
        if (newAreaId) {
            const areaDetail = strategyAreaDetails.value.find(area => area.areaId === newAreaId);
            if (areaDetail) {
                selectedAreaDetail.value = areaDetail;
                fillAreaConfigForm(areaDetail);
            }
        } else {
            selectedAreaDetail.value = null;
            resetAreaConfigForm();
        }
    });
    
    // =====================================
    // 主要功能方法
    // =====================================
    
    /**
     * 加载策略的区域详情列表
     */
    const loadStrategyAreaDetails = async () => {
        if (!currentStrategyId.value) return;
        
        loading.value = true;
        try {
            const result = await window.FreightApp.api.get(`/strategy-area-pricing/strategy/${currentStrategyId.value}/area-details`);
            
            if (result.code === 0) {
                strategyAreaDetails.value = result.data || [];
                console.log('加载策略区域详情成功:', strategyAreaDetails.value.length, '个区域');
                
                // 如果之前有选中的区域，尝试恢复选中状态
                if (selectedAreaId.value) {
                    const stillExists = strategyAreaDetails.value.find(area => area.areaId === selectedAreaId.value);
                    if (!stillExists) {
                        selectedAreaId.value = '';
                    }
                }
            } else {
                strategyAreaDetails.value = [];
                Utils.showMessage('加载区域详情失败: ' + result.msg, true);
            }
        } catch (error) {
            console.error('加载策略区域详情失败:', error);
            strategyAreaDetails.value = [];
            Utils.showMessage('加载区域详情失败', true);
        } finally {
            loading.value = false;
        }
    };
    
    /**
     * 选择区域
     */
    const selectArea = (areaId) => {
        if (hasUnsavedChanges.value) {
            if (!confirm('当前有未保存的更改，是否继续？')) {
                return;
            }
        }
        selectedAreaId.value = areaId;
        isEditing.value = false;
    };
    
    /**
     * 开始编辑
     */
    const startEditing = () => {
        if (!selectedAreaDetail.value) {
            window.showMessage('请先选择一个区域', true);
            return;
        }
        isEditing.value = true;
    };
    
    /**
     * 取消编辑
     */
    const cancelEditing = () => {
        if (hasUnsavedChanges.value) {
            if (!confirm('确定要取消编辑吗？未保存的更改将丢失。')) {
                return;
            }
        }
        isEditing.value = false;
        if (selectedAreaDetail.value) {
            fillAreaConfigForm(selectedAreaDetail.value);
        }
    };
    
    /**
     * 保存区域配置
     */
    const saveAreaConfiguration = async () => {
        if (!validateAreaConfigForm()) {
            return;
        }
        
        saving.value = true;
        try {
            // 构造完整配置数据
            const configData = {
                strategyId: currentStrategyId.value,
                areaId: selectedAreaId.value,
                firstWeightKg: parseFloat(areaConfigForm.firstWeightKg),
                firstWeightFee: parseFloat(areaConfigForm.firstWeightFee),
                additionalWeightKg: parseFloat(areaConfigForm.additionalWeightKg),
                additionalWeightFee: parseFloat(areaConfigForm.additionalWeightFee),
                volumetricWeightRatio: parseFloat(areaConfigForm.volumetricWeightRatio),
                status: areaConfigForm.status,
                weightSegmentRules: areaConfigForm.weightSegmentRules.map(rule => ({
                    id: rule.id || null,
                    upperBound: parseFloat(rule.upperBound),
                    freight: parseFloat(rule.freight),
                    operation: rule.id ? 'UPDATE' : 'ADD'
                })),
                operator: 'admin' // 实际项目中从当前登录用户获取
            };
            
            const result = await api.post('/strategy-area-pricing/complete-config/save', configData);
            
            if (result.code === 0) {
                Utils.showMessage('保存成功');
                isEditing.value = false;
                // 重新加载数据
                await loadStrategyAreaDetails();
            } else {
                Utils.showMessage('保存失败: ' + result.msg, true);
            }
        } catch (error) {
            console.error('保存区域配置失败:', error);
            Utils.showMessage('保存失败', true);
        } finally {
            saving.value = false;
        }
    };
    
    // =====================================
    // 重量区间规则管理
    // =====================================
    
    /**
     * 添加重量区间规则
     */
    const addWeightRule = () => {
        if (!validateNewWeightRule()) {
            return;
        }
        
        const newRule = {
            id: null, // 新规则没有ID
            upperBound: newWeightRule.upperBound,
            freight: newWeightRule.freight,
            weightRangeDisplay: `≤${newWeightRule.upperBound} kg`
        };
        
        areaConfigForm.weightSegmentRules.push(newRule);
        
        // 重新排序规则
        areaConfigForm.weightSegmentRules.sort((a, b) => 
            parseFloat(a.upperBound) - parseFloat(b.upperBound)
        );
        
        // 重置新增表单
        resetNewWeightRule();
        newWeightRule.isAdding = false;
    };
    
    /**
     * 删除重量区间规则
     */
    const removeWeightRule = (index) => {
        if (confirm('确定要删除这个重量区间规则吗？')) {
            areaConfigForm.weightSegmentRules.splice(index, 1);
        }
    };
    
    /**
     * 开始添加重量规则
     */
    const startAddingWeightRule = () => {
        newWeightRule.isAdding = true;
    };
    
    /**
     * 取消添加重量规则
     */
    const cancelAddingWeightRule = () => {
        resetNewWeightRule();
        newWeightRule.isAdding = false;
    };
    
    // =====================================
    // 表单处理方法
    // =====================================
    
    /**
     * 填充区域配置表单
     */
    const fillAreaConfigForm = (areaDetail) => {
        areaConfigForm.strategyId = areaDetail.strategyId || currentStrategyId.value;
        areaConfigForm.areaId = areaDetail.areaId;
        areaConfigForm.areaName = areaDetail.areaName;
        areaConfigForm.firstWeightKg = areaDetail.firstWeightKg || '';
        areaConfigForm.firstWeightFee = areaDetail.firstWeightFee || '';
        areaConfigForm.additionalWeightKg = areaDetail.additionalWeightKg || '';
        areaConfigForm.additionalWeightFee = areaDetail.additionalWeightFee || '';
        areaConfigForm.volumetricWeightRatio = areaDetail.volumetricWeightRatio || '';
        areaConfigForm.status = areaDetail.status || 1;
        areaConfigForm.weightSegmentRules = [...(areaDetail.weightSegmentRules || [])];
    };
    
    /**
     * 重置区域配置表单
     */
    const resetAreaConfigForm = () => {
        areaConfigForm.strategyId = '';
        areaConfigForm.areaId = '';
        areaConfigForm.areaName = '';
        areaConfigForm.firstWeightKg = '';
        areaConfigForm.firstWeightFee = '';
        areaConfigForm.additionalWeightKg = '';
        areaConfigForm.additionalWeightFee = '';
        areaConfigForm.volumetricWeightRatio = '';
        areaConfigForm.status = 1;
        areaConfigForm.weightSegmentRules = [];
    };
    
    /**
     * 重置新增重量规则表单
     */
    const resetNewWeightRule = () => {
        newWeightRule.upperBound = '';
        newWeightRule.freight = '';
    };
    
    // =====================================
    // 验证方法
    // =====================================
    
    /**
     * 验证区域配置表单
     */
    const validateAreaConfigForm = () => {
        const { firstWeightKg, firstWeightFee, additionalWeightKg, additionalWeightFee, volumetricWeightRatio } = areaConfigForm;
        
        // 验证首重重量
        if (!firstWeightKg || isNaN(firstWeightKg) || parseFloat(firstWeightKg) < 0) {
            Utils.showMessage('首重重量不能为负数', true);
            return false;
        }
        
        // 验证首重资费
        if (!firstWeightFee || isNaN(firstWeightFee) || parseFloat(firstWeightFee) < 0) {
            Utils.showMessage('首重资费不能为负数', true);
            return false;
        }
        
        // 验证续重重量
        if (!additionalWeightKg || isNaN(additionalWeightKg) || parseFloat(additionalWeightKg) < 0) {
            Utils.showMessage('续重重量不能为负数', true);
            return false;
        }
        
        // 验证续重资费
        if (!additionalWeightFee || isNaN(additionalWeightFee) || parseFloat(additionalWeightFee) < 0) {
            Utils.showMessage('续重资费不能为负数', true);
            return false;
        }
        
        // 验证抛重比
        if (!volumetricWeightRatio || isNaN(volumetricWeightRatio) || parseFloat(volumetricWeightRatio) < 0) {
            Utils.showMessage('抛重比不能为负数', true);
            return false;
        }
        
        return true;
    };
    
    /**
     * 验证新增重量规则
     */
    const validateNewWeightRule = () => {
        const { upperBound, freight } = newWeightRule;
        
        if (!upperBound || parseFloat(upperBound) < 0) {
            Utils.showMessage('请输入有效的重量上限', true);
            return false;
        }
        
        if (!freight || parseFloat(freight) < 0) {
            Utils.showMessage('请输入有效的区间资费', true);
            return false;
        }
        
        // 检查重复
        const existingRule = areaConfigForm.weightSegmentRules.find(rule => 
            parseFloat(rule.upperBound) === parseFloat(upperBound)
        );
        
        if (existingRule) {
            Utils.showMessage('该重量上限已存在', true);
            return false;
        }
        
        return true;
    };
    
    // =====================================
    // 导出的方法和数据
    // =====================================
    
    return {
        // 数据
        currentStrategyId,
        strategyAreaDetails,
        loading,
        saving,
        selectedAreaId,
        selectedAreaDetail,
        isEditing,
        showAreaConfigModal,
        areaConfigForm,
        newWeightRule,
        
        // 计算属性
        currentWeightRules,
        hasUnsavedChanges,
        
        // 方法
        loadStrategyAreaDetails,
        selectArea,
        startEditing,
        cancelEditing,
        saveAreaConfiguration,
        addWeightRule,
        removeWeightRule,
        startAddingWeightRule,
        cancelAddingWeightRule,
        resetAreaConfigForm,
        resetNewWeightRule
    };
}
